/*
 * Created on Jun 3, 2005
 *
 */
package com.erclab.internal.xpresso.handlers;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;


import org.apache.commons.dbutils.ResultSetHandler;

import com.erclab.internal.xpresso.dataAccess.GenericResultSet;

/**
 * @author Enrique Rodriguez.
 *
 */
public class GenericResultsHandler implements ResultSetHandler {

	public GenericResultsHandler(){
	}
	

	/* (non-Javadoc)
	 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
	 */
	public Object handle(ResultSet rs) throws SQLException {
		GenericResultSet grs = new GenericResultSet();
		ResultSetMetaData rsmd = rs.getMetaData();
		
		// Set the column count
		int numberOfColumns = rsmd.getColumnCount();		
		grs.setNumberOfColumns(numberOfColumns);
		
		// Get the column names
		String[] columnNames = new String[numberOfColumns];
		for(int i=1 ; i <= numberOfColumns; i++ ){
			columnNames[i - 1] = rs.getMetaData().getColumnName(i);
		}
		grs.setColumnNames(columnNames);
				
		// Create the results
		while (rs.next()){
			// Create new row
			String[] row = new String[numberOfColumns];
			for (int i = 0; i< numberOfColumns; i++){
				row[i] = rs.getString(i+1);
			}
			grs.addRow(row);
		}
		return grs;	
	}

}
